package database

import (
	_ "github.com/go-sql-driver/mysql"
	"github.com/google/wire"
	"github.com/jinzhu/gorm"
	"github.com/pkg/errors"
	"github.com/spf13/viper"
	"go.uber.org/zap"
)

type Options struct {
	URL   string `yaml:"url"`
	Debug bool
}

func NewOptions(v *viper.Viper, logger *zap.Logger) (*Options, error) {
	var (
		err error
		o   = new(Options)
	)
	if err = v.UnmarshalKey("db", o); err != nil {
		return nil, errors.Wrap(err, "unmarshal db options error")
	}
	return o, nil
}

func New(o *Options) (*gorm.DB, error) {
	db, err := gorm.Open("mysql", o.URL)
	if err != nil {
		return nil, errors.Wrap(err, "gorm open database error")
	}
	return db, nil
}

var ProviderSet = wire.NewSet(New, NewOptions)
